﻿using HslCommunication;
using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OKDebug
{
    public partial class FrmXiMenZiPLC : Form
    {
        private SiemensS7Net _siemensPLCS;
        public FrmXiMenZiPLC()
        {
            InitializeComponent();
        }

        private void btnConnectXiMenZiPLC_Click(object sender, EventArgs e)
        {
            if (btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                if (MessageBox.Show("是否断开连接？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    _siemensPLCS.ConnectClose();
                    btnConnectXiMenZiPLC.ForeColor = SystemColors.ControlText;
                    btnConnectXiMenZiPLC.BackColor = SystemColors.Control;
                    btnConnectXiMenZiPLC.Text = "连接";
                };

                return;
            }

            string ip = this.txtXiMenZiPLCIP.Text.Trim();
            string port = this.txtXiMenZiPLCPort.Text.Trim();

            if (string.IsNullOrEmpty(ip))
            {
                this.txtXiMenZiPLCIP.Focus();
                MessageBox.Show("IP为空！");
                return;
            }

            if (string.IsNullOrEmpty(port))
            {
                this.txtXiMenZiPLCPort.Focus();
                MessageBox.Show("端口为空！");
                return;
            }

            int _port = Convert.ToInt32(port);
            _siemensPLCS = new SiemensS7Net(SiemensPLCS.S1200, ip) { Port = _port };
            _siemensPLCS.ConnectTimeOut = 3000;
            var result = _siemensPLCS.ConnectServer();
            if (result.IsSuccess)
            {
                btnConnectXiMenZiPLC.ForeColor = Color.White;
                btnConnectXiMenZiPLC.BackColor = Color.Green;
                btnConnectXiMenZiPLC.Text = "已连接";
                MessageBox.Show("连接成功！");
            }
            else
            {
                MessageBox.Show("连接失败！" + result.Message);
            }
        }

        private void btnXiMenZiCharRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiCharAddr.Text.Trim();
            OperateResult<byte[]> operateResult=_siemensPLCS.Read(strAddress,2);
            if (!operateResult.IsSuccess)
            {
                MessageBox.Show("读取失败!"+ operateResult.Message);
                return;
            }

            if (operateResult.Content.Length < 2)
            {
                MessageBox.Show("读取的字节长度不对!");
                return;
            }

            int _length = (int)operateResult.Content[1] + 2;
            operateResult = _siemensPLCS.Read(strAddress, (ushort)_length);
            if (!operateResult.IsSuccess)
            {
                MessageBox.Show("读取失败!" + operateResult.Message);
                return;
            }

            this.txtXiMenZiCharContent.Text = Encoding.Default.GetString(operateResult.Content, 2, _length - 2);
        }

        private void btnXiMenZiCharWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiCharAddr.Text.Trim();
            string str = this.txtXiMenZiCharContent.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiCharAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            var result = _siemensPLCS.Write(strAddress, GetPLCStringByteArray(str));
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }

        /// <summary>
        /// 获取西门子PLC字符串数组--String
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static byte[] GetPLCStringByteArray(string str)
        {
            byte[] value = Encoding.Default.GetBytes(str);
            byte[] head = new byte[2];
            head[0] = Convert.ToByte(254);
            head[1] = Convert.ToByte(str.Length);
            value = head.Concat(value).ToArray();
            return value;
        }

        private void btnXiMenZiFloatRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiFloatAddr.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiFloatAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            var re = _siemensPLCS.ReadFloat(strAddress);
            if (re.IsSuccess)
            {
                this.txtXiMenZiFloatContent.Text = re.Content.ToString();
            }
            else
            {
                MessageBox.Show("读取失败！" + re.Message);
            }
        }

        private void btnXiMenZiFloatWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiFloatAddr.Text.Trim();
            string str = this.txtXiMenZiFloatContent.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiFloatContent.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(str))
            {
                this.txtXiMenZiFloatContent.Focus();
                MessageBox.Show("内容为空!");
                return;
            }

            byte[] buffer = new byte[4];
            float val = Convert.ToSingle(str);
            BitConverter.GetBytes(val).CopyTo(buffer, 0);
            buffer = buffer.Reverse().ToArray();
            var result = _siemensPLCS.Write(strAddress, buffer);
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }

        private void btnXiMenZiShortRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiShortAddr.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiShortAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            var re = _siemensPLCS.ReadUInt16(strAddress);
            if (re.IsSuccess)
            {
                this.txtXiMenZiShortContent.Text = re.Content.ToString();
            }
            else
            {
                MessageBox.Show("读取失败！" + re.Message);
            }
        }

        private void btnXiMenZiShortWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiShortAddr.Text.Trim();
            string str = this.txtXiMenZiShortContent.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiShortAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(str))
            {
                this.txtXiMenZiShortContent.Focus();
                MessageBox.Show("内容为空!");
                return;
            }

            byte[] buffer = new byte[2];
            ushort val = Convert.ToUInt16(str);
            BitConverter.GetBytes(val).CopyTo(buffer, 0);
            buffer = buffer.Reverse().ToArray();
            var result = _siemensPLCS.Write(strAddress, buffer);
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }

        private void btnXiMenZiIntRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiIntAddr.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiIntAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            var re = _siemensPLCS.ReadInt16(strAddress);
            if (re.IsSuccess)
            {
                this.txtXiMenZiIntContent.Text = re.Content.ToString();
            }
            else
            {
                MessageBox.Show("读取失败！" + re.Message);
            }
        }

        private void btnXiMenZiIntWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiIntAddr.Text.Trim();
            string str = this.txtXiMenZiIntContent.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiIntAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(str))
            {
                this.txtXiMenZiIntContent.Focus();
                MessageBox.Show("内容为空!");
                return;
            }

            byte[] buffer = new byte[2];
            short val = Convert.ToInt16(str);
            BitConverter.GetBytes(val).CopyTo(buffer, 0);
            buffer = buffer.Reverse().ToArray();
            var result = _siemensPLCS.Write(strAddress, buffer);
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }

        private void btnXiMenZiByteRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiByteAddr.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiByteAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            var re = _siemensPLCS.ReadByte(strAddress);
            if (re.IsSuccess)
            {
                this.txtXiMenZiByteContent.Text = re.Content.ToString();
            }
            else
            {
                MessageBox.Show("读取失败！" + re.Message + " " + (re.Message.Contains("数据块长度") ? "确认PLC是否已经启用PUT/GET" : ""));
            }
        }

        private void btnXiMenZiByteWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiByteAddr.Text.Trim();
            string str = this.txtXiMenZiByteContent.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiByteAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(str))
            {
                this.txtXiMenZiByteContent.Focus();
                MessageBox.Show("内容为空!");
                return;
            }

            byte[] buffer = new byte[1];
            byte val = Convert.ToByte(str);
            buffer[0] = val;
            var result = _siemensPLCS.Write(strAddress, buffer);
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }

        private void btnXiMenZiBitRead_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            string strAddress = this.txtXiMenZiBitAddr.Text.Trim();
            string index = this.txtXiMenZiBitIndex.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiBitAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(index))
            {
                this.txtXiMenZiBitIndex.Focus();
                MessageBox.Show("位索引为空!");
                return;
            }

            ushort _index = Convert.ToUInt16(index);
            var re = _siemensPLCS.Read(strAddress, 1);
            if (re.IsSuccess)
            {
                int val = (re.Content[0] >> _index) & 0x01;
                this.txtXiMenZiBitContent.Text = val.ToString();
            }
            else
            {
                MessageBox.Show("读取失败！" + re.Message + " " + (re.Message.Contains("数据块长度") ? "确认PLC是否已经启用PUT/GET" : ""));
            }
        }

        private void btnXiMenZiBitWrite_Click(object sender, EventArgs e)
        {
            if (!btnConnectXiMenZiPLC.Text.Equals("已连接"))
            {
                MessageBox.Show("未连接！");
                return;
            }

            if (MessageBox.Show("谨慎操作！确认写入吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            };

            string strAddress = this.txtXiMenZiBitAddr.Text.Trim();
            string str = this.txtXiMenZiBitContent.Text.Trim();
            string index = this.txtXiMenZiBitIndex.Text.Trim();
            if (string.IsNullOrEmpty(strAddress))
            {
                this.txtXiMenZiBitAddr.Focus();
                MessageBox.Show("地址为空!");
                return;
            }

            if (string.IsNullOrEmpty(index))
            {
                this.txtXiMenZiBitIndex.Focus();
                MessageBox.Show("位索引为空!");
                return;
            }

            if (string.IsNullOrEmpty(str))
            {
                this.txtXiMenZiBitContent.Focus();
                MessageBox.Show("内容为空!");
                return;
            }

            byte oldVal;
            ushort _index = Convert.ToUInt16(index);
            var re = _siemensPLCS.Read(strAddress, 1);
            if (re.IsSuccess)
            {
                oldVal = re.Content[0];
            }
            else
            {
                MessageBox.Show("读取原值失败！" + re.Message);
                return;
            }

            byte[] buffer = new byte[1];
            oldVal = Common.SetbitValue(oldVal, _index + 1, "1".Equals(str) ? true : false);
            buffer[0] = oldVal;
            var result = _siemensPLCS.Write(strAddress, buffer);
            if (result.IsSuccess)
            {
                MessageBox.Show("写入成功！");
            }
            else
            {
                MessageBox.Show("写入失败！" + result.Message);
            }
        }
    }
}
